﻿using System;
using UnityEngine;

public sealed class TimeManager : Singleton<TimeManager>
{
    private DateTime m_serverDate;
    private DateTime m_UNIXStartTime;
    private long local_to_server_dur;

    public TimeManager()
    { 
        m_UNIXStartTime = TimeZone.CurrentTimeZone.ToLocalTime(new DateTime(1970, 1, 1, 0, 0, 0, 0));
        
    }

    public void UpdateServerTime(uint value)
    {
        //秒
        m_serverDate = m_UNIXStartTime.AddSeconds(value);
        local_to_server_dur = (m_serverDate.Ticks - DateTime.Now.Ticks) / 10000000;
    }


    /*
     * 获取当前的时间戳
     * 以秒为单位
    */
    public long NowUtcTime
    {
        get
        {
            //return (DateTime.Now.Ticks - DateTime.Parse("1970-01-01 00:00:00").Ticks) / 10000000;
            DateTime startTime = m_UNIXStartTime;//TimeZone.CurrentTimeZone.ToLocalTime(new DateTime(1970, 1, 1, 0, 0, 0, 0));
            DateTime nowTime = DateTime.Now;
            long unix = (nowTime.Ticks - startTime.Ticks) / 10000000 + local_to_server_dur;
            return unix;
        }
    }
    public DateTime serverDate
    {
        get
        {
            return m_serverDate;
        }
    }
    /*
     * 获取当前的时间戳
     * 以毫秒为单位
    */
    public long NowUtcTimeMS
    {
        get
        {
            DateTime startTime = TimeZone.CurrentTimeZone.ToLocalTime(new DateTime(1970, 1, 1, 0, 0, 0, 0));
            DateTime nowTime = DateTime.Now;
            long unix = (nowTime.Ticks - startTime.Ticks) / 10000 + local_to_server_dur * 1000;
            return unix;
        }
    }
    /*public static DateTime FROM_UNIXTIME(long timeStamp)// Unix时间戳转成时间
    {
        return DateTime.Parse("1970-01-01 00:00:00").AddSeconds(timeStamp);
    }*/
    /*
     * 时间转成Unix时间戳
     * 以秒为单位
    */
    public long UNIX_TIMESTAMP(DateTime dateTime)
    {
        //return (dateTime.Ticks - DateTime.Parse("1970-01-01 00:00:00").Ticks) / 10000000;
        DateTime startTime = m_UNIXStartTime;//TimeZone.CurrentTimeZone.ToLocalTime(new DateTime(1970, 1, 1, 0, 0, 0, 0));
        long unix = (dateTime.Ticks - startTime.Ticks) / 10000000;
        return unix;
    }
    /*
     *  Unix时间戳转成时间
     * 参数unix为毫秒
     */
    public DateTime FROM_UNIXMSTIME(long unix)
    {
        DateTime time = DateTime.MinValue;
        DateTime startTime = m_UNIXStartTime;//TimeZone.CurrentTimeZone.ToLocalTime(new DateTime(1970, 1, 1));
        time = startTime.AddMilliseconds(unix);
        return time;
    }
    /*
     * 由时间段转成指定的时间格式
     * 
    */
    public string TIMESLOT_To_FormatString(long time,bool second=true,bool minute=true,bool hour=true,string str=":")
    {
        int m_hour=(int)time/60/60;
        int m_minute=(int)(time/60)%60;
        int m_second=(int)time%60;
        string timeStr = "";
        if (hour)
        {
            timeStr += checkTimeNum(m_hour) + str;
        }
        if (minute)
        {
            timeStr += checkTimeNum(m_minute);
        }
        if(second)
        {
            timeStr+=str+checkTimeNum(m_second);
        }
        return timeStr;
    }
    /*
     * 由UNIX转成指定的时间格式
     * 
     * */
    public string UNIX_To_FormatString(long unix, bool second = true, bool minute = true, bool hour = true, string str = ":", bool day = false, bool mouth = false, bool year = false,bool millisecond = false)
    {
        DateTime dateTime = FROM_UNIXMSTIME(unix * 1000);
        return TIME_To_FormatString(dateTime, second, minute, hour, str, day, mouth, year,millisecond);
    }
    /*
     * 由UNIX转成指定的时间格式
     * 
     * */
    public string UNIXMS_To_FormatString(long unix, bool second = true, bool minute = true, bool hour = true, string str = ":", bool day = false, bool mouth = false, bool year = false, bool millisecond = false)
    {
        DateTime dateTime = FROM_UNIXMSTIME(unix);
        return TIME_To_FormatString(dateTime, second, minute, hour, str, day, mouth, year, millisecond);
    }

    public string UNIXMS_To_FormatString_split(long unix, string split,bool second = true, bool minute = true, bool hour = true, string str = ":", bool day = false, bool mouth = false, bool year = false, bool millisecond = false)
    {
        DateTime dateTime = FROM_UNIXMSTIME(unix*1000);
        return TIME_To_FormatString(dateTime, second, minute, hour, str, day, mouth, year, millisecond,split);
    }

    /*由dateTime转成指定的时间格式
     * 
     * */
    public string TIME_To_FormatString(DateTime dateTime, bool second = true, bool minute = true, bool hour = true, string str = ":", bool day = false, bool mouth = false, bool year = false, bool millisecond = false,string split="-")//由dateTime转成指定的时间格式
    {
        string timeStr = "";
        if (year)
        {
            timeStr += dateTime.Year+split;
        }
        if (mouth)
        {
            timeStr += checkTimeNum(dateTime.Month) + split;
        }
        if (day)
        {
            timeStr += checkTimeNum(dateTime.Day) + "  ";
        }
        if (hour)
        {
            timeStr += checkTimeNum(dateTime.Hour) + str;
        }
        if (minute)
        {
            timeStr += checkTimeNum(dateTime.Minute);
        }
        if (second)
        {
            timeStr += str + checkTimeNum(dateTime.Second);
        }
        if (millisecond)
        {
            timeStr += str + checkTimeNum(dateTime.Millisecond);
        }
        return timeStr;
    }
    public string checkTimeNum(int time)
    {
        if (time >= 10)
        {
            return time.ToString();
        }
        else
        {
            return "0" + time;
        }
    }

    public DayOfWeek getServerFactDayOfWeek(uint gameLogicalDailyUpdateHour)
    {
        DateTime tempServerDate = m_UNIXStartTime.AddSeconds(NowUtcTime - gameLogicalDailyUpdateHour * 3600);
        return tempServerDate.DayOfWeek;
    }

    //------------
    private static DateTime BaseTime = new DateTime(1970, 1, 1);
    /// <summary>
    /// 根据时间戳计算出实际的DateTime
    /// </summary>
    /// <param name="timeStanpt"></param>
    /// <returns></returns>
    public DateTime FromUnixTime(long timeStanpt)
    {
        return new DateTime((timeStanpt + 8 * 60 * 60) * 10000000 + BaseTime.Ticks);
    }
    /// <summary>
    /// 根据datetime转为时间戳
    /// </summary>
    /// <param name="datetime"></param>
    /// <returns></returns>
    public long FromDataTime(DateTime datetime) {
        return (datetime.Ticks - BaseTime.Ticks) / 10000000 - 8 * 60 * 60;
    }

    /// <summary>
    /// 之前某一个时间到现在的差值
    /// </summary>
    /// <param name="everTimeStamp"></param>
    /// <returns></returns>
    public int PassedTimeUntilNow(long everTimeStamp)
    {
        return (int)(NowUtcTime - everTimeStamp);
    }

    /// <summary>
    /// 获取当天某个时间
    /// </summary>
    /// <param name="time">22:00</param>
    /// <returns></returns>
    public int FromTimeString(string time) {
        Debug.Log("FromTimeString>> " + time);
        string[] arrTime = time.Split(':');
        if (arrTime.Length != 2) {
            return (int)NowUtcTime;
        }
        DateTime curDt = FromUnixTime((int)NowUtcTime);
        int year = curDt.Year;
        int month = curDt.Month;
        int day = curDt.Day;
        //int second = curDt.Second;
        int curHour = int.Parse(arrTime[0]);
        int curMinute = int.Parse(arrTime[1]);
        DateTime dt = new DateTime(year, month, day, curHour, curMinute, 0);
        int result = (int)FromDataTime(dt);
        return result;
    }
    /// <summary>
    /// 获取下一天某个时间
    /// </summary>
    /// <param name="time">22:00</param>
    /// <returns></returns>
    public int FromNextDayTimeString(string time)
    {
        string[] arrTime = time.Split(':');
        if (arrTime.Length != 2)
        {
            return (int)NowUtcTime;
        }
        DateTime curDt = FromUnixTime((int)NowUtcTime);
        DateTime nextDt = curDt.AddDays(1);
             
        int year = nextDt.Year;
        int month = nextDt.Month;
        int day = nextDt.Day;
        //int second = nextDt.Second;
        int curHour = int.Parse(arrTime[0]);
        int curMinute = int.Parse(arrTime[1]);
        DateTime dt = new DateTime(year, month, day, curHour, curMinute, 0);
        int result = (int)FromDataTime(dt);
        return result;
    }

    /// <summary>
    /// 获取当前时间戳
    /// </summary>
    /// <returns></returns>
    public int GetCurrentTime() {
        return (int)NowUtcTime;
    }
    public DateTime GetCurrentDateTime() {
        return FromUnixTime((int)NowUtcTime);
    }
    public  string FormatSecondToTime(int seconds)
    {
        string str = "";
        int hour = 0;
        int minute = 0;
        int second = 0;
        if (seconds > 60)
        {
            minute = seconds / 60;
            second = seconds % 60;
        }
        else
        {
            second = seconds;
        }
        if (minute > 60)
        {
            hour = minute / 60;
            minute = minute % 60;
        }
        string strHour = hour.ToString();
        string strMinute = minute.ToString();
        string strSecond = second.ToString();
        
        if (hour < 10) {
            strHour = "0" + hour.ToString();
        }
        if (minute < 10)
        {
            strMinute = "0" + minute.ToString();
        }
        if (second < 10)
        {
            strSecond = "0" + second.ToString();
        }
        str = strHour + ":" + strMinute + ":" + strSecond;
        return str;
    }

    public string FormatSecondToTime(int seconds,bool showHour,bool showMin)
    {
        string str = "";
        int hour = 0;
        int minute = 0;
        int second = 0;
        if (seconds > 60)
        {
            minute = seconds / 60;
            second = seconds % 60;
        }
        else
        {
            second = seconds;
        }
        if (minute > 60)
        {
            hour = minute / 60;
            minute = minute % 60;
        }
        if (!showHour) {
            minute = minute + hour * 60;
            hour = 0;
        }
        if (!showMin) {
            second = second + minute * 60;
            minute = 0;
        }

        string strHour = hour.ToString();
        string strMinute = minute.ToString();
        string strSecond = second.ToString();

        if (hour < 10)
        {
            strHour = "0" + hour.ToString();
        }
        if (minute < 10)
        {
            strMinute = "0" + minute.ToString();
        }
        if (second < 10)
        {
            strSecond = "0" + second.ToString();
        }
        if (showHour) {
            str = str + strHour + ":";
        }
        if (showMin) {
            str = str + strMinute + ":";
        }
        str =str + strSecond;
        return str;
    }


    // 获得时间差（秒）
    public int GetTimeDiff(string timeStamp)
    {
        DateTime dateTimeStart = TimeZone.CurrentTimeZone.ToLocalTime(new DateTime(1970, 1, 1));
        ///var ttt = timeStamp + "0000000";
        long lTime = long.Parse(timeStamp + "0000000");
        TimeSpan toNow = new TimeSpan(lTime);
        DateTime endDt = dateTimeStart.Add(toNow);
        if (DateTime.Now > endDt) {
            endDt = endDt.AddDays(1);
        }
        TimeSpan ts1 = new TimeSpan(endDt.Ticks);
        TimeSpan ts2 = new TimeSpan(DateTime.Now.Ticks);

        var diff = ts1 - ts2;

        int diffSecond = (int)diff.TotalSeconds;

        return diffSecond;
    }

}

